'''
Created on Mar 28, 2013

@author: Gabriel
'''
import xbmcaddon
import xbmc
import xbmcgui
import threading

DATA_HOST = "192.168.1.2:8088"

KEY_BUTTON_BACK = 275
KEY_KEYBOARD_ESC = 61467

ACTION_PARENT_DIR = 9
ACTION_PREVIOUS_MENU = 10
ACTION_NEXT_ITEM = 14
ACTION_NAV_BACK = 92

class EpisodeCountersView (xbmcgui.WindowXML) :
    _WINDOW = 14002
    _TABLE_HEADER = 401
    _TABLE_LIST = 402

    episodeMgr = None
    databaseMgr = None


    def onAction(self, action):
        if action == ACTION_PREVIOUS_MENU:
            self.close()
            
    def onClick(self, controlId):
        if controlId == 301 : 
            self.reset()
        if controlId == 302 : 
            self.close()
        if controlId == 402 : 
            currentItem = self.getFocusedItem()
            
            dialog = xbmcgui.Dialog()
            response = dialog.numeric(0, "Enter Current Episode:")            
#            response = mc.ShowDialogSelect("Enter Current Episode:", self.getEpisodesCountForDisplay(currentItem.getLabel()))
            self.updateFocusedItemCounter(int(response))
    
    def setup(self, episodeMgr, databaseMgr):
        self.episodeMgr = episodeMgr
        self.databaseMgr = databaseMgr

    def onInit(self):
        self.updateHeader()
        self.refreshTable()

    def reset(self):
        self.episodeMgr.reset()
        self.refreshTable()
        
    def updateHeader(self):
        headerRow = []
        headerRow.append(xbmcgui.ListItem('Series'))
        headerRow.append(xbmcgui.ListItem('Series'))
        headerRow.append(xbmcgui.ListItem('Series'))
        headerRow.append(xbmcgui.ListItem('Series'))
        self.getControl(self._TABLE_HEADER).reset()
        self.getControl(self._TABLE_HEADER).addItems(headerRow)
    
    def refreshTable(self):
        currentItemIndex = self.getControl(self._TABLE_LIST).getSelectedItem()
        self.getControl(self._TABLE_LIST).reset()
        self.getControl(self._TABLE_LIST).addItems(self.episodeMgr.getEpisodeCountersForDisplay())
#        if currentItemIndex > len(self.getControl(self._TABLE_LIST).count()) - 1:
#            currentItemIndex = len(self.getControl(self._TABLE_LIST).getItems()) - 1
#        self.getControl(self._TABLE_LIST).setFocusedItem(currentItemIndex)

    def getFocusedItem(self) :
        return self.getControl(self._TABLE_LIST).getSelectedItem()

    def updateFocusedItemCounter(self, newCounter):
        focusedItem = self.getFocusedItem()
        self.episodeMgr.setCurrentEpisode(focusedItem.getLabel(), newCounter)
        self.refreshTable()

    def getEpisodesCountForDisplay(self, seriesName):
        rangeList = range(self.databaseMgr.getEpisodeCount(seriesName))
        return map(str, rangeList)


class ScheduleView (xbmcgui.WindowXML) :
    _SCHEDULE_HEADER = 401
    _SCHEDULE_LIST = 402

    scheduleMgr = None
    databaseMgr = None
    
    def setup(self, scheduleMgr, databaseMgr):
        self.scheduleMgr = scheduleMgr
        self.databaseMgr = databaseMgr
        # self.databaseMgr.downloadDatabase('http://192.168.1.4:8088/Development/videosDatabase.json')
        
    def onAction(self, action):
        if action == ACTION_PREVIOUS_MENU:
            self.close()
#        if action == ACTION_LEFT and controId == 402:
#            mc.GetActiveWindow().GetControl(300).SetFocus()

            
    def onClick(self, controlId):
        if controlId == 301 : 
            self.addRow()
        if controlId == 302 : 
            self.removeRow()
        if controlId == 303 : 
            self.close()
        if controlId == 304 : 
            self.downloadSchedule('http://' + DATA_HOST + '/Development/schedule.json')            
        if controlId == 402 : 
            if self.isCurrentEntryTime():
                dialog = xbmcgui.Dialog()
                response = dialog.numeric(2, "Enter time in HH:MM format")            
                self.updateCurrentEntry(response)
            else:
                selectionList = self.getAvailableVideos()
                dialog = xbmcgui.Dialog()
                response = dialog.select("Select Schedule Item", selectionList)            
                self.updateCurrentEntry(selectionList[response])

    def onInit(self):
        self.updateHeader()
        self.refreshTable()
      
    def updateHeader(self):
        headerRow = []
        item = xbmcgui.ListItem()
        item.setLabel('Time')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Sun')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Mon')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Tue')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Wed')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Thu')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Fri')
        headerRow.append(item)
        item = xbmcgui.ListItem()
        item.setLabel('Sat')
        headerRow.append(item)
        self.getControl(self._SCHEDULE_HEADER).reset()
        self.getControl(self._SCHEDULE_HEADER).addItems(headerRow)

    def downloadSchedule(self, url):
        print('Updating database')
        self.scheduleMgr.download(url)
        self.refreshTable()
        
    def removeRow(self) :
        self.scheduleMgr.removeRow(self.getFocusedItem().getProperty('time'))
        self.refreshTable()

    def addRow(self) :
        selectedTime = self.getFocusedItem().getProperty('time')
        self.scheduleMgr.addNextRow(selectedTime)
        self.refreshTable()

    def getFocusedItem(self) :
        return self.getControl(self._SCHEDULE_LIST).getSelectedItem()
        
        
    def refreshTable(self) :
        self.getControl(self._SCHEDULE_LIST).reset()
        self.getControl(self._SCHEDULE_LIST).addItems(self.scheduleMgr.getScheduleForDisplay())

    def isCurrentEntryTime(self):
        currentItem = self.getFocusedItem()
        print currentItem.getProperty('isTime')
        return currentItem.getProperty('isTime') == "True"
        
    def updateCurrentEntry(self, newValue):
        currentItem = self.getFocusedItem()
        if currentItem.getProperty('isTime') == "True" :
            timep = str(currentItem.getProperty('time'))
            self.scheduleMgr.updateScheduleTimeEntry(newValue, timep)
        else :
            timep = str(currentItem.getProperty('time'))
            day = str(currentItem.getProperty('day'))
            self.scheduleMgr.updateScheduleEntry(newValue, timep, day)
        self.refreshTable()

    def getAvailableVideos(self):
        availableVideos = self.databaseMgr.getShowsForDisplay()
        availableVideos.insert(0, '<movie>')
        availableVideos.insert(0, '<show>')
        return availableVideos

#
# Controls the main window
#
class MainWindowView (xbmcgui.WindowXML) : 
    # UI elements
    _WINDOW = 1
    _TIMER_LABEL = 23
    _WAIT_TIME = 10
    state = "STOPPED"
    player = None
    quitApp = False
    
    def setup(self, databaseMgr, scheduleMgr, episodeMgr):
        self.databaseMgr = databaseMgr
        self.scheduleMgr = scheduleMgr
        self.episodeMgr = episodeMgr
        self.player = _RelaxeePlayer()
        self.player.setup(scheduleMgr, databaseMgr, episodeMgr)

    def onAction(self, action):
        actionID = action.getId()
        if actionID in (ACTION_PREVIOUS_MENU, ACTION_NAV_BACK, ACTION_PARENT_DIR):
            self.quitApp = True
        
        
    def onClick(self, controlId):
        if controlId == 21 : 
            self.run()
        if controlId == 22 : 
            self.stop()
        if controlId == 24 : 
            self.updateVideosDatabase('http://' + DATA_HOST + '/Development/videosDatabase.json')
        if controlId == 25 : 
            self.stop()
            scheduleView = ScheduleView("schedule.xml", xbmcaddon.Addon().getAddonInfo('path').decode('utf-8'), "default", "720p")
            scheduleView.setup(self.scheduleMgr, self.databaseMgr)
            scheduleView.doModal()
            del scheduleView
        if controlId == 26 : 
            self.stop()
            episodeCountersView = EpisodeCountersView("episodeCounters.xml", xbmcaddon.Addon().getAddonInfo('path').decode('utf-8'), "default", "720p")
            episodeCountersView.setup(self.episodeMgr, self.databaseMgr)
            episodeCountersView.doModal()
            del episodeCountersView
            
    def run(self):
        self.show()
        self.start()
        print('Starting iteration')
        while not self.quitApp :
            if self.state is "RUNNING" :
                print('Loop is running')
                self.counter -= 1
                labelControl = self.getControl(self._TIMER_LABEL)
                labelControl.setLabel(str(self.counter))
                if self.counter == 0 :
                    self.playing()
                    self.player.playNext()
            # Playback is over? Then start over
            elif self.state is "PLAYING" and not self.player.isPlaying() :
                self.start()
            xbmc.sleep(1000)
        self.close()
        print('Loop is over')

    def start(self):
        print ('START')
        self.state = "RUNNING"
        self.__resetCounter()
    
    def playing(self):
        print ('PLAYING')
        self.state = "PLAYING"
        
    def stop(self):
        print ('STOP')
        self.state = "STOPPED"

    def updateVideosDatabase(self, url):
        self.stop()
        print('Updating database')
        self.player.databaseMgr.download(url)

    def __resetCounter(self):
        self.counter = self._WAIT_TIME


class _RelaxeePlayer(xbmc.Player):
    episodeMgr = None
    scheduleMgr = None
    databaseMgr = None

    def setup(self, scheduleMgr, databaseMgr, episodeMgr):
        self.episodeMgr = episodeMgr
        self.scheduleMgr = scheduleMgr
        self.databaseMgr = databaseMgr

    def playNext(self):
        playNextEntry = str(self.scheduleMgr.getNextScheduleEntry())
        incrementEpisode = True
        
        # If the schedule specifies only a genre, then play a random video of the genre    
        if playNextEntry == '<show>' :
            playNextPath = str(self.databaseMgr.getRandomEpisodePath())
            incrementEpisode = False
        else :
            if playNextEntry == '<movie>' : 
                playNextEntry = self.databaseMgr.getRandomMovieEntry()
            currentEpisode = self.episodeMgr.getCurrentEpisode(playNextEntry)
            print playNextEntry
            print currentEpisode
            playNextPath = self.databaseMgr.getEpisodePath(playNextEntry, currentEpisode)

        print('Next program: '+ playNextEntry)
        print('File: '+ playNextPath.encode('cp1252'))
    
        self.play(playNextPath)
    
        if incrementEpisode :
            # Increment the episode count
            self.episodeMgr.incrementCurrentEpisode(playNextEntry, self.databaseMgr.getEpisodeCount(playNextEntry))

